<template>
  <el-popover placement="bottom" title="过滤" width="155" trigger="click">
    <el-checkbox
        label="全选/全不选"
        v-model="checkAll"
        @change="checkAllHandler"
        :indeterminate="isIndeterminate"
      ></el-checkbox>
    <el-checkbox-group v-model="checked" @change="changeHandler">
      <el-checkbox
        v-for="i in labels"
        :key="i.recNo"
        :label="i.label"
      ></el-checkbox>
    </el-checkbox-group>
    <el-button slot="reference">筛选</el-button>
  </el-popover>
</template>

<script>
export default {
  props: ["tableLabel"],
  data () {
    return {
      checked: [],
      labels: [],
      checkAll: true,
      isIndeterminate: false
    };
  },
  methods: {
    changeHandler (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.labels.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.labels.length;
      this.$bus.$emit("tableFilter", this.checked);
    },
    checkAllHandler (bool) {
      const labels = this.labels.map(item => item.label);
      this.checked = bool ? [...labels] : [];
      this.$bus.$emit("tableFilter", this.checked);
      this.isIndeterminate = false;
    }
  },
  watch: {
    //监视表格更新情况，实时更新过滤器选项
    tableLabel: {
      immediate: true,
      deep: true,
      handler (newVal) {
        const labels = JSON.parse(JSON.stringify(newVal));
        labels.forEach((item, index) => {
          if (item.label === "操作") {
            labels.splice(index, 1);
          }
        });
        this.checked = labels.map((item) => item.label);
        this.labels = labels;
        this.checkAll = true;
      }
    }
  },
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
